﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using Kalman.Extensions;

namespace QuDao
{
    /// <summary>
    /// 商品类别业务对象（处理数据表mall_category相关的业务逻辑）
    /// </summary>
    public sealed partial class CategoryBO : SingletonBase<CategoryBO>
    {
        readonly IFreeSql fsql;
        public CategoryBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }
        
        /// <summary>
        /// 获取商品类别
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
        	if (id <= 0) return default;
            var item = fsql.Select<Category>().Where(a => a.CategoryID == id).ToOne<T>();
            return item;
        }
        
        public Category GetItem(int id)
        {
        	return GetItem<Category>(id);
        }
        
        /// <summary>
        /// 获取商品类别详情
        /// </summary>
        /// <param name="id">商品类别ID</param>
        /// <returns></returns>
        public CategoryDetailsDto GetDetails(int id)
        {
            var dto = GetItem<CategoryDetailsDto>(id);
            return dto;
        }

        /// <summary>
        /// 获取商品类别数据列表
        /// </summary>
        /// <param name="tid">租户ID</param>
        /// <returns></returns>
        public List<CategoryDto> GetList(int tid)
        {
            var list = fsql.Select<Category>().Where(a => a.TID == tid).OrderByDescending(a => a.SortFlag).ToList<CategoryDto>();
            return list;
        }
        
        /// <summary>
        /// 获取商品类别数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<Category>().Where(a => ids.Contains(a.CategoryID)).ToList<T>();
            return list;
        }
        
        /// <summary>
        /// 新增商品类别
        /// </summary>
        public int Add(CategoryAddDto dto)
        {
        	var entity = dto.CopyTo<Category>();
        	
            entity.CreateTime = DateTime.Now;
            entity.ModifyTime = DateTime.Now;
            entity.CategoryID = (int)fsql.Insert(entity).ExecuteIdentity();
            return entity.CategoryID;
        }

        /// <summary>
        /// 修改商品类别
        /// </summary>
        public int Modify(CategoryModifyDto dto)
        {
            var item = GetItem<Category>(dto.CategoryID) ?? throw new AppException($"商品类别不存在：{dto.CategoryID}");

            var update = fsql.Update<Category>(dto.CategoryID).Set(a => a.ModifyTime, DateTime.Now);
            
            if (dto.CategoryName != item.CategoryName) update.Set(a => a.CategoryName, dto.CategoryName);
			if (dto.SortFlag != item.SortFlag) update.Set(a => a.SortFlag, dto.SortFlag);
            //if (dto.IsEnable != item.IsEnable) update.Set(a => a.IsEnable, dto.IsEnable);
						
			return update.ExecuteAffrows();
        }


		public int SetEnable(int id, bool isEnable)
        {
            return fsql.Update<Category>(id).Set(a => a.IsEnable, isEnable).ExecuteAffrows();
        }
		/// <summary>
        /// 删除商品类别数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return 0;
        	return fsql.Delete<Category>().Where(a => ids.Contains(a.CategoryID)).ExecuteAffrows();
        }
        
        /// <summary>
        /// 删除商品类别数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int id)
        {
        	return fsql.Delete<Category>(id).ExecuteAffrows();
        }
        
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<Category> Query(PagingRequest req, int tid = 0)
        {
        	if (req == null) throw new AppException("查询数据不能为空");
        	
            var select = fsql.Select<Category>().WhereIf(tid > 0, a => a.TID == tid);
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    case "CategoryID":
                        select.Where(a => a.CategoryID == int.Parse(item.Value));
                        break;
                    case "CategoryName":
                        select.Where(a => a.CategoryName.Contains(item.Value));
                        break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.CategoryID);//默认排序
            }

            //var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<Category>();
            return new PagingResult<Category>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }
        
    }
}
